package com.yty.aop;


import com.yty.Utils.CurrentHolder;
import com.yty.dao.OperateLogMapper;
import com.yty.pojo.OperateLog;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import java.time.LocalDateTime;
import java.util.Arrays;


/*
*
* 用于记录日志得切面类
* 用于记录增，删，改得操作日志，操作人id，操作时间，操作方法，操作参数，返回值，耗时
* */
@Aspect
@Component
public class OperationLogAspect {

    @Autowired
    private OperateLogMapper operateLogMapper;

    @Around("@annotation(com.yty.annotation.LogOperation)")
    public Object logOperation(ProceedingJoinPoint joinPoint) throws Throwable {
        // 获取当前时间
        Long startTime = System.currentTimeMillis();
        //执行方法
        Object result = joinPoint.proceed();
        //获取结束时间，统计耗时
        Long endTime = System.currentTimeMillis();
        Long costTime = endTime - startTime;
        //获取执行方法得类，方法名，结果，当前时间，参数并封装到操作日志对象中
        OperateLog operateLog = new OperateLog();
        //获取当前线程中的当前用户id，并设置到操作日志对象中
        operateLog.setOperateEmpId(CurrentHolder.getCurrentId());
        operateLog.setOperateTime(LocalDateTime.now());
        operateLog.setClassName(joinPoint.getTarget().getClass().getName());
        operateLog.setMethodName(joinPoint.getSignature().getName());
        //获取得参数是一个数组，所以需要转换为字符串
        operateLog.setMethodParams(Arrays.toString(joinPoint.getArgs()));
        operateLog.setReturnValue(result.toString());
        operateLog.setCostTime(costTime);

        //插入到数据库中
        operateLogMapper.insert(operateLog);
        return result;
    }

}
